package cn.strive.eams.purchase.service.impl;

import cn.strive.eams.application.mapper.ApplicationMapper;
import cn.strive.eams.application.pojo.entity.Application;
import cn.strive.eams.base.enmus.ApplicationStatusEnum;
import cn.strive.eams.purchase.mapper.PurchaseMapper;
import cn.strive.eams.purchase.pojo.dto.PurchaseSaveParam;
import cn.strive.eams.purchase.pojo.entity.Purchase;
import cn.strive.eams.purchase.service.PurchaseService;
import cn.strive.eams.virtual.pojo.entity.Virtual;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
@Service
public class PurchaseServiceImpl implements PurchaseService {
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    @Override
    public void savePurchase(PurchaseSaveParam purchaseSaveParam) {
        log.debug("保存虚拟资产业务:purchaseSaveParam={}",purchaseSaveParam);
        Purchase purchase = new Purchase();
        BeanUtils.copyProperties(purchaseSaveParam,purchase);
            purchase.setCreateTime(new Date());
            purchaseMapper.insert(purchase);

        Application application = new Application();
        BeanUtils.copyProperties(purchaseSaveParam,application);
        application.setApplyId(purchase.getId());
        application.setApplyNumber(generateApplyNumber());
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        log.debug("application={}",application);
        applicationMapper.insert(application);
    }

    private String generateApplyNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);

        // 初始化四位数字部分，从0000开始
        int numberPart = 0;

        String applyNumber;
        do {
            String formattedNumber = String.format("%04d", numberPart);
            applyNumber = "APPLY" + currentDateStr + formattedNumber;

            // 检查是否有重复的昵称
            if (!isApplyNumberExists(applyNumber)) {
                break;
            }

            // 如果存在重复，则将数字部分增加10
            numberPart += 10;
        } while (true);

        return applyNumber;
    }

    private boolean isApplyNumberExists(String applyNumber) {
        return applicationMapper.existsByApplyNumber(applyNumber) > 0;
    }
}
